/*******************************************************************
 *   > File Name: daemon_process.c
 *   > Author: fly
 *   > Mail: lf.ye@samoon.net
 *   > Create Time: 2021-03-01  1/09  12:42:07 +0800
 *================================================================*/

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <time.h>
#include <syslog.h>

void init_daemon(void){
    pid_t pid;
    int i;

    pid = fork();
    if(pid < 0)
    {
        printf("Error Fork\n");
        exit(1);
    }
    else if(pid > 0)
    {
        exit(0);
    }

    setsid();
    chdir("/");
    umask(0);

    for(i = 0; i< getdtablesize(); i++)
    {
        close(i);
    }
}

int main(int argc, char* argv[])
{
    init_daemon();

    int fd;
    char *buf = "This is Daemon";
    char str_buf[128] = {0};
    time_t timep;
    
    openlog("daemon_syslog", LOG_PID|LOG_PERROR, LOG_DAEMON);
    while(1)
    {
        if((fd = open("/opt/daemon.log", O_CREAT|O_WRONLY|O_TRUNC, 0600)) <0)
        {
            printf("Open file error.\n");
            syslog(LOG_ERR, "open");
            syslog(LOG_ERR, "daemon syslog test");
            exit(1);
        }

        bzero(str_buf, 128);
        time(&timep);
        snprintf(str_buf, 128, "%s :%s ", buf, ctime(&timep));

        write(fd, str_buf, strlen(str_buf));
        close(fd);
        sleep(2);
    }

    closelog();

    return 0;
}
